import React, { useState, useEffect, useCallback } from "react";
import {
  Button,
  Form,
  Input,
  Select,
  Space,
  Upload,
  InputNumber,
  DatePicker,
  Modal,
  message,
} from "antd";
import QRCode from "qrcode.react";
import { PlusOutlined } from "@ant-design/icons";
import { handleUpdate, dictType, provinceList } from "@/api";
import moment from "moment";
import { debounce } from "lodash";

const { Option } = Select;
const { TextArea } = Input;

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

const normFile = (e: any) => {
  if (Array.isArray(e)) {
    return e;
  }
  return e?.fileList;
};

// const CardPage: React.FC = () => {
export default function CardPage() {
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);

  const onGenderChange = (value: string) => {
    switch (value) {
      case "male":
        form.setFieldsValue({ note: "Hi, man!" });
        break;
      case "female":
        form.setFieldsValue({ note: "Hi, lady!" });
        break;
      case "other":
        form.setFieldsValue({ note: "Hi there!" });
        break;
      default:
    }
  };

  const onFinish = (values: any) => {
    console.log(values);
  };

  const onReset = () => {
    form.resetFields();
  };

  const onFill = () => {
    form.setFieldsValue({ note: "Hello world!", gender: "male" });
  };

  const submit = () => {
    // setVisible(true);
    try {
      form?.validateFields().then((values) => {
        console.log(values);
        const { expectedDeliveryTime } = values;
        handleUpdate({
          ...values,
          expectedDeliveryTime: expectedDeliveryTime
            ? moment(expectedDeliveryTime).format("YYYY-MM-DD HH:mm:ss")
            : null,
          orderTime: moment().format("YYYY-MM-DD HH:mm:ss"),
        }).then((res) => {
          const { data, status, msg } = res;
          if (status === 200 && data) {
            form.resetFields();
            message.success(msg || "新增成功");
            return;
          } else {
            message.error(msg || "新增失败");
          }
        });
      });
    } catch (error) {
      console.log(error);
    }
  };

  const handleOk = () => {
    console.log("handleOk");
  };

  const handleCancel = () => {
    console.log("handleCancel");
    setVisible(false);
  };

  useEffect(() => {
    getCampanyData("FSLX");
    // getCampanyData("SFCS");
    // getData()
    getCampanyData("GS");
  }, []);

  const [campanyData, setCampanyData] = useState([]);

  const [campanyData1, setCampanyData1] = useState([]);

  const [clothData, setClothData] = useState([]);

  const fun = debounce((value) => {
    getData(value);
  }, 500);

  const getData = (val) => {
    const result = provinceList({ addr: val });
    result.then((res) => {
      if (res.status === 200) {
        setCampanyData(res?.data?.map((data) => {
          return { label: data.addr, value: data.addr };
        }));
      } else {
        message.error(res.msg || "导入失败");
      }
    });
  };

  const getCampanyData = (code) => {
    dictType({ categoryCode: code, pageIndex: 1, pageSize: 999 }).then(
      (data) => {
        console.log(data, "datadata111");
        if (data?.status) {
          if (code === "SFCS") {
            setCampanyData(
              data?.data?.records?.map((item) => {
                return { label: item.value, value: item.id };
              })
            );
          } else if (code === "FSLX") {
            const arr = data?.data?.records?.map((item) => {
              return { label: item.value, value: item.id };
            });
            setClothData(arr);
          }
          if (code === "GS") {
            setCampanyData1(
              data?.data?.records?.map((item) => {
                return { label: item.value, value: item.id };
              })
            );
          }
        } else {
          message.error(data?.msg || data?.code || "请求错误");
        }
      }
    );
  };

  return (
    <>
      <Form
        {...layout}
        form={form}
        name="control-hooks"
        onFinish={onFinish}
        style={{ maxWidth: 600 }}
      >
        <Form.Item
          name="companyName"
          label="公司"
          // rules={[{ required: true }]}
        >
          <Select
            placeholder="请选择"
            // onChange={onGenderChange}
            showSearch
            allowClear
            options={campanyData1}
          />
        </Form.Item>
        <Form.Item
          name="orderNumber"
          label="订单编码"
          rules={[{ required: true }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>

        <Form.Item
          name="customerName"
          label="姓名"
          rules={[{ required: true }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item name="customerAge" label="年龄">
          <InputNumber style={{ width: "100%" }} min={0} defaultValue={0} />
        </Form.Item>
        <Form.Item
          name="customerPhone"
          label="电话"
          rules={[{ required: true }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          name="clothingType"
          label="服饰类型"
          // rules={[{ required: true }]}
        >
          <Select
            placeholder="请选择"
            // onChange={onGenderChange}
            showSearch
            allowClear
            options={clothData}
          />
        </Form.Item>
        <Form.Item
          name="specification"
          label="规格型号"
          rules={[{ required: true }]}
        >
          <Input style={{ width: "100%" }} placeholder="请输入" />
        </Form.Item>
        <Form.Item name="quantity" label="数量">
          <InputNumber style={{ width: "100%" }} min={0} />
        </Form.Item>

        <Form.Item
          name="unitPrice"
          label="单价"
          // rules={[{ required: true }]}
        >
          <InputNumber style={{ width: "100%" }} min={0} />
        </Form.Item>
        <Form.Item
          name="totalAmount"
          label="金额"
          // rules={[{ required: true }]}
        >
          <InputNumber style={{ width: "100%" }} min={0} />
        </Form.Item>
        <Form.Item
          label="预计交付时间"
          name="expectedDeliveryTime"
          valuePropName="fileList"
          // getValueFromEvent={normFile}
        >
          <DatePicker style={{ width: "100%" }} format="YYYY-MM-DD HH:mm:ss" />
        </Form.Item>
        <Form.Item
          name="customerAddress"
          label="收件地址"
          rules={[{ required: true }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          name="customerProvinceCity"
          label="省份城市"
          // rules={[{ required: true }]}
        >
          <Select
            onSearch={(v) => {
              if (!v) return;
              fun(v);
            }}
            placeholder="请先输入后再选择"
            // onChange={onGenderChange}
            showSearch
            allowClear
            options={campanyData}
          />
        </Form.Item>
        <Form.Item name="additionalRequirements" label="额外要求">
          <TextArea placeholder="请输入订单备注" rows={4} />
        </Form.Item>
        <Form.Item {...tailLayout}>
          <Space>
            <Button type="primary" htmlType="submit" onClick={() => submit()}>
              新建
            </Button>
            <Button htmlType="button" onClick={onReset}>
              重置
            </Button>
            {/* <Button type="link" htmlType="button" onClick={onFill}>
            Fill form
          </Button> */}
          </Space>
        </Form.Item>
      </Form>

      <Modal
        // size="mini"
        title="二维码"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确认"
        cancelText="取消"
        footer={false}
      >
        <div style={{ width: "100%", textAlign: "center" }}>
          <QRCode value="https://www.example.com" />
          <p>订单新建成功，可右键保存二维码</p>
        </div>
      </Modal>
    </>
  );
}

// export default Card;
CardPage.route = { [MENU_PATH]: "/list/card" };
